package common.listener;

import org.apache.commons.lang3.SerializationUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.io.Serializable;

/**
 * Created by Administrator on 2016/7/29.
 */
@WebListener
public class SessionListener<T> implements HttpSessionListener {
    private static ApplicationContext applicationContext;
    private static RedisTemplate<String, String> redisTemplate;
    private static WebApplicationContext webApplicationContext;

    public void sessionDestroyed(HttpSessionEvent se) {
        webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(se.getSession().getServletContext());
        redisTemplate = (RedisTemplate<String, String>) webApplicationContext.getBean("redisTemplate");
        redisTemplate.opsForSet().remove("sessionIds", se.getSession().getId());
        se.getSession().invalidate();//session失效
    }

    public void save(final String key, Object value) {
        final byte[] vbytes = SerializationUtils.serialize((Serializable) value);
        redisTemplate.execute(new RedisCallback<Object>() {
            public Object doInRedis(RedisConnection connection)
                    throws DataAccessException {
                connection.set(redisTemplate.getStringSerializer().serialize(key), vbytes);
                return null;
            }
        });
    }

    public T get(final String key) {
        T t = redisTemplate.execute(new RedisCallback<T>() {
            public T doInRedis(RedisConnection connection)
                    throws DataAccessException {
                byte[] keybytes = redisTemplate.getStringSerializer().serialize(key);
                if (connection.exists(keybytes)) {
                    byte[] valuebytes = connection.get(keybytes);
                    T value = SerializationUtils.deserialize(valuebytes);
                    return value;
                }
                return null;
            }
        });
        return t;
    }

    public void sessionCreated(HttpSessionEvent se) {
        //用户访问量
      /*  webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(se.getSession().getServletContext());
        redisTemplate = (RedisTemplate<String, String>) webApplicationContext.getBean("redisTemplate");
        //将对象存入redis
        save("key", new User());
        T u = get("key");
        //反序列化对象


        System.out.printf("");*/
    }


}
